import logging
import asyncio
from flask import jsonify
from flask_restful import Resource, reqparse

# 项目导入
from app.controller import collect_api  # 绝对导入
from app.models.system_access_config import SystemAccessConfig  # 绝对导入
from app.extensions import db  # 绝对导入
from browser.webui.components.test import collect_menu_sql_data
from browser.api.db.model_service import process_directory
from app.services.collect_service import get_or_create_conversation_id, write_conversation_record

# 日志配置
logger = logging.getLogger(__name__)

"""
自动采集接口
"""
class CollectApi(Resource):
    """开始自动采集"""
    def post(self):
        try:
            # 1. 解析请求参数
            parser = reqparse.RequestParser()
            parser.add_argument("id", type=int, required=True, location="json", help="请输入查询的配置ID")
            parser.add_argument("prompt", type=str, required=True, location="json", help="请输入查询的提示信息")
            parser.add_argument("conversation_id", type=str, required=False, location="json")
            args = parser.parse_args()

            # 2. 验证配置是否存在
            system_config = db.session.query(SystemAccessConfig).filter(SystemAccessConfig.id == args["id"]).first()
            if not system_config:
                logger.warning(f'配置ID {args["id"]} 不存在')
                return jsonify({
                    'status': 'error',
                    'message': f'配置ID {args["id"]} 不存在'
                })

            # 3. 获取或创建会话ID
            conversation_id = get_or_create_conversation_id(args["prompt"])

            # 4. 写入会话记录
            write_conversation_record(args["prompt"], conversation_id)

            # 5. 执行菜单数据采集
            result_data = asyncio.run(collect_menu_sql_data(system_config.to_dict(), conversation_id))
            
            # 6. 保存采集结果
            process_directory(result_data)
            
            logger.info(f"菜单采集成功完成，配置ID: {args['id']}")
            return jsonify({
                'status': 'success',
                'data': system_config.to_dict()
            })

        except Exception as e:
            logger.error(f'查询配置时发生错误: {str(e)}', exc_info=True)
            return jsonify({
                'status': 'error',
                'message': f'查询配置时发生错误: {str(e)}'
            })




# 注册路由
collect_api.add_resource(CollectApi, "/start")
